<template>
  <div class="dashboard-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <el-tab-pane label="设备状态" name="dashboard">
        <transition name="fade" mode="out-in">
          <el-row :gutter="10">
            <el-col v-if="showLeft" :span="10">
              <!-- uart Port Transmit/Receive Status -->
              <el-card class="equal-height-card">
                <div slot="header" class="dashboard-header">串口收发状态</div>
                <el-table :data="uartPortStatus" :height="tableHeight" border size="mini" fit>
                  <el-table-column prop="port" label="Port"></el-table-column>
                  <el-table-column prop="td" label="TD">
                    <template>
                      <!-- <el-badge
                        :value="scope.row.td ? '●' : ''"
                        class="status-badge"
                        :class="{ active: scope.row.td }"
                      ></el-badge> -->
                      <el-button type="success" circle size="mini"></el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="tc" label="TC">
                    <template>
                      <el-button type="info" circle size="mini"></el-button>
                      <!-- <el-badge
                        :value="scope.row.tc ? '●' : ''"
                        class="status-badge"
                        :class="{ active: scope.row.tc }"
                      ></el-badge> -->
                    </template>
                  </el-table-column>
                  <el-table-column prop="rd" label="RD">
                    <!-- <template slot-scope="scope">
                      <el-badge
                        :value="scope.row.rd ? '●' : ''"
                        class="status-badge"
                        :class="{ active: scope.row.rd }"
                      ></el-badge>
                    </template> -->
                    <el-button type="success" circle size="mini"></el-button>
                  </el-table-column>
                  <el-table-column prop="rc" label="RC">
                    <el-button type="info" circle size="mini"></el-button>
                    <!-- <template slot-scope="scope">
                      <el-badge
                        :value="scope.row.rc ? '●' : ''"
                        class="status-badge"
                        :class="{ active: scope.row.rc }"
                      ></el-badge>
                    </template> -->
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>

            <el-col :span="24">
              <el-row :gutter="10">
                <!-- Device Status Information -->
                <el-col :span="24">
                  <el-card
                    class="equal-height-card"
                  >
                    <div slot="header" class="dashboard-header">
                      设备状态信息
                    </div>
                    <el-form
                      ref="sysInfoForm"
                      v-loading.lock="loading"
                      label-width="150px"
                      class="device-status-form"
                      :hide-required-asterisk="true"
                      :model="sysInfo"
                      :rules="sysInfoRules"
                    >
                      <el-row :gutter="10">
                        <el-col :span="18" :offset="2">
                          <el-form-item label="设备别名" prop="aliasName">
                            <el-input v-model="sysInfo.aliasName" size="medium"></el-input>
                          </el-form-item>
                          <el-form-item label="产品型号" prop="devType">
                            <el-input v-if="isRoot" v-model="sysInfo.devType" size="medium"></el-input>
                            <div v-else class="dashboard-text">{{ sysInfo.devType }}</div>
                          </el-form-item>
                          <el-form-item label="设备SN" prop="sn">
                            <el-input v-if="isRoot" v-model="sysInfo.sn" size="medium"></el-input>
                            <div v-else class="dashboard-text">{{ sysInfo.sn }}</div>

                          </el-form-item>
                          <el-form-item label="硬核版本" prop="hardVersion">
                            <!-- <el-input v-if="isRoot" v-model="sysInfo.hardVersion" size="medium"></el-input> -->
                            <div class="dashboard-text">{{ sysInfo.hardVersion }}</div>

                          </el-form-item>
                          <el-form-item label="软件版本" prop="softVersion">
                            <!-- <el-input v-if="isRoot" v-model="sysInfo.softVersion" size="medium"></el-input> -->
                            <div class="dashboard-text">{{ sysInfo.softVersion }}</div>

                          </el-form-item>
                          <el-form-item label="运行时间">
                            <div class="dashboard-text">{{ sysInfo.runTime }}</div>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="10" class="button-row">
                        <el-col :span="12">
                          <el-button type="primary" size="mini" @click="getSysInfo(1)">刷新</el-button>
                        </el-col>
                        <el-col :span="12">
                          <el-button type="danger" size="mini" @click="setSysInfo">设置</el-button>
                        </el-col>
                      </el-row>
                    </el-form>
                  </el-card>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </transition>
      </el-tab-pane>

      <el-tab-pane label="统计信息" name="uartNetworkStats">
        <transition name="fade" mode="out-in">
          <el-row :gutter="10">
            <el-col :span="24">
              <!-- UART and Network Port Statistics -->
              <el-card class="equal-height-card">
                <div slot="header" class="dashboard-header">
                  串口、网口收发统计信息
                </div>
                <el-row
                  v-loading.lock="loading1"
                  :gutter="10"
                >
                  <el-col :span="12">
                    <el-table :data="portStatistics.uart" :height="tableHeight" border size="mini" fit>
                      <el-table-column prop="id" label="串口号">
                        <template slot-scope="scope">
                          <span>S{{ scope.row.id }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="baud" label="发时钟"></el-table-column>
                      <el-table-column prop="recvBaud" label="收时钟"></el-table-column>
                      <el-table-column prop="sendNum" label="发送数据"></el-table-column>
                      <el-table-column prop="recvNum" label="接收数据"></el-table-column>

                    </el-table>
                  </el-col>
                  <el-col :span="12">
                    <el-table :data="portStatistics.udp" :height="tableHeight" border size="mini" fit>
                      <el-table-column prop="ethName" label="网卡名"></el-table-column>
                      <el-table-column prop="port" label="端口"></el-table-column>
                      <el-table-column prop="sendNum" label="发送数据"></el-table-column>
                      <el-table-column prop="recvNum" label="接收数据"></el-table-column>
                    </el-table>
                    <el-row :gutter="10" class="button-row">
                      <el-col :span="12">
                        <el-button type="primary" size="mini" @click="manualRefresh">刷新</el-button>
                      </el-col>
                      <el-col :span="12">
                        <el-button type="danger" size="mini" @click="clearPortStatistics">清零</el-button>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </transition>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'

export default {
  name: 'Dashboard',
  data() {
    return {
      tableHeight: 'calc(100vh - 300px)',
      showLeft: false,
      activeTab: 'dashboard',
      loading: false,
      loading1: false,
      timeoutId: null, // 用于存储 timeoutId 的 ID
      sysInfo: {
        aliasName: '',
        devType: '',
        runTime: '',
        sn: '',
        hardVersion: '',
        softVersion: ''
      },
      sysInfoRules: {
        aliasName: [
          { required: true, message: '请输入设备别名', trigger: 'blur' }
        ],
        devType: [
          { required: true, message: '请输入产品型号', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入设备SN', trigger: 'blur' }
        ],
        hardVersion: [
          { required: true, message: '请输入硬核版本', trigger: 'blur' }
        ],
        softVersion: [
          { required: true, message: '请输入软件版本', trigger: 'blur' }
        ]
      },
      uartPortStatus: [
        { port: 'S1', td: true, tc: false, rd: true, rc: false },
        { port: 'S2', td: false, tc: true, rd: false, rc: true },
        { port: 'S3', td: true, tc: false, rd: true, rc: false },
        { port: 'S4', td: false, tc: true, rd: false, rc: true },
        { port: 'S5', td: true, tc: false, rd: true, rc: false },
        { port: 'S6', td: false, tc: true, rd: false, rc: true },
        { port: 'S7', td: true, tc: false, rd: true, rc: false },
        { port: 'S8', td: false, tc: true, rd: false, rc: true },
        { port: 'S9', td: true, tc: false, rd: true, rc: false },
        { port: 'S10', td: false, tc: true, rd: false, rc: true },
        { port: 'S11', td: true, tc: false, rd: true, rc: false },
        { port: 'S12', td: false, tc: true, rd: false, rc: true },
        { port: 'S13', td: true, tc: false, rd: true, rc: false },
        { port: 'S14', td: false, tc: true, rd: false, rc: true },
        { port: 'S15', td: true, tc: false, rd: true, rc: false },
        { port: 'S16', td: false, tc: true, rd: false, rc: true }
      ],
      portStatistics: {
        uart: [],
        udp: []
      }
    }
  },
  computed: {
    ...mapGetters(['username', 'level']),
    isRoot() {
      return this.level === 0
    }
  },
  created() {
    this.getSysInfo()
  },
  beforeDestroy() {
    this.stopPolling() // 组件销毁时停止轮询
  },
  methods: {
    handleTabClick(tab) {
      if (this.activeTab === 'uartNetworkStats') {
        this.startPolling()
      } else {
        this.getSysInfo()
        this.stopPolling()
      }
    },
    getPortStatistics(flag = 0) {
      this.loading1 = true
      this.$store.dispatch('device/getPortStatistics').then(res => {
        this.loading1 = false
        this.portStatistics.uart = res.uart
        this.portStatistics.udp = res.udp
        if (flag === 1) {
          this.$message.success('统计状态信息获取成功')
        }

        // 继续轮询
        if (this.activeTab === 'uartNetworkStats') {
          this.timeoutId = setTimeout(this.getPortStatistics, 2000)
        }
      }).catch(() => {
        this.loading1 = false
        // 请求失败后，仍然继续轮询
        if (this.activeTab === 'uartNetworkStats') {
          this.timeoutId = setTimeout(this.getPortStatistics, 2000)
        }
      })
    },
    clearPortStatistics() {
      this.loading1 = true
      this.$store.dispatch('device/clearPortStatistics').then(res => {
        this.loading1 = false
        this.portStatistics.uart = []
        this.portStatistics.udp = []
        this.$message.success('统计状态信息清除成功')
      }).catch(() => {
        this.loading1 = false
      })
    },
    getSysInfo(flag = 0) {
      this.loading = true
      this.$store.dispatch('device/getSysInfo').then(res => {
        this.loading = false
        this.$nextTick(() => this.$refs.sysInfoForm.clearValidate())
        this.sysInfo = res.sysInfo
        if (flag === 1) {
          this.$message.success('设备状态信息获取成功')
        }
      }).catch(() => {
        this.loading = false
      })
    },
    setSysInfo() {
      this.$refs.sysInfoForm.validate((valid) => {
        // eslint-disable-next-line no-unused-vars
        // const { runTime, ...rest } = this.sysInfo
        let SysInfoParams = {}
        if (this.isRoot) {
          // eslint-disable-next-line no-unused-vars
          const { runTime, ...rest } = this.sysInfo
          SysInfoParams = { ...rest, userLevel: this.level }
        } else {
          // eslint-disable-next-line no-unused-vars
          const { devType, softVersion, sn, hardVersion, runTime, ...rest } = this.sysInfo
          SysInfoParams = { ...rest, userLevel: this.level }
        }
        if (valid) {
          this.loading = true
          this.$store.dispatch('device/setSysInfo', SysInfoParams).then(res => {
            this.loading = false
            this.$nextTick(() => this.$refs.sysInfoForm.clearValidate())
            this.$message.success('设备状态信息更新成功')
          }).catch((err) => {
            console.log(err)
            this.loading = false
          })
          return true
        } else {
          this.$message.warning('设备状态信息校验失败')
          return false
        }
      })
    },
    refreshStatistics() {
    },
    // 启动轮询
    startPolling() {
      this.stopPolling() // Ensure any existing polling is stopped before starting a new one
      this.getPortStatistics() // 立即执行一次
    },
    // 停止轮询
    stopPolling() {
      if (this.timeoutId) {
        clearTimeout(this.timeoutId)
        this.timeoutId = null
      }
    },
    manualRefresh() {
      this.stopPolling() // Stop any ongoing polling
      this.getPortStatistics(1) // Fetch data immediately
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-container {
  margin: 20px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.dashboard-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.equal-height-card {
  display: flex;
  flex-direction: column;
}

.button-row {
  text-align: center;
  margin-top: 10px;
}

.status-badge {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  &.active {
    background-color: green;
  }
}

.dashboard-text {
  font-size: 14px;
  line-height: 40px;
}
</style>
